/*
Copyright (c) 2012, 2013 Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions 
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

function analysisRadio(refresh){
	getTimeRange();
	if (typeof refresh == 'undefined'){
		var refresh = false
	}
	if (document.getElementById("analysisRadio1").checked){
		$('#smoothGroup').show()
		$('#hooDiv').show()
		analysisType = 'economizer'
		updateTree(projectName); //update BMS tree--function from bmsTagtree.js
		buildEconomizerTree();
		var projectId = sessvars.sessionObj['projectId']
		$.ajax({
			type: "POST",
			url: '/pmp/energy/',
			data: {'projectIdChange': projectId},
			success: function(data){
				$('#economizerHeading').html(data)
			}
		});
	}
}

function buildEconomizerTree(load, data){
 	if (load == true){
		var jsonData = {  
         	"ajax" : {  
	            "url" : "/pmp/cfload/",  
	            "data" : $('form#configDrop').serializeObject(),
	            "success" : function (){
	            	//value = string($('select#id_for_name').val())
	            var configFileName = $('select#id_for_name').find("option:selected").text()
	            $('#id_form_name').val(configFileName)	
	            },
         	}  
     	}
    }
    else {
	 	var jsonData = {  
	        "data" : [{ data: "MAT", children: [], state: "open" ,  attr: {id: "id1", rel:"folder", class:"jstree-drop"},},
	         { data: "RAT", children: [], state: "open", attr: {id: "id2", rel:"folder", class:"jstree-drop"},},
	         { data: "OAT", children: [], state: "open", attr: {id: "id3", rel:"folder", class:"jstree-drop"},},
	         { data: "SAT", children: [], state: "open", attr: {id: "id4", rel:"folder", class:"jstree-drop"},},
	         { data: "SA.SPT", children: [], state: "open", attr: {id: "id5", rel:"folder", class:"jstree-drop"},},
	         { data: "CHW_VLV", children: [], state: "open", attr: {id: "id6", rel:"folder", class:"jstree-drop"},}],
	    }
    }
	$("#treeSelections").jstree({ 
		"json_data" :  jsonData,  
 		"types" : {
			"valid_children" : [ "root" ],
			"types" : {
				"root" : {"valid children" : "folder"},
				"default" : {},
				"folder" : {
					"valid_children" : [ "default", "folder", "file" ],
					"icon" : {
						"image" : "/static/smap/img/folder.png",
					},
				},
			}
		},
		"plugins" : [ "themes", "json_data", "ui", "dnd", "crrm", "types","hotkeys"],
		"ui": {"select_multiple_modifier" : "alt"},
    })
   .bind("dblclick.jstree", function(event) {
           var node = $(event.target).closest("li");
           if ($(node).hasClass("jstree-leaf")) {
             $("#__tree").jstree("select_node", node);
           } else {
             $("#__tree").jstree("toggle_node", node);
           }
         })
   .bind("move_node.jstree", function(event , data) {        
         //create paths to parse for setpoint analysis
         data.rslt.o.each(function(i){
         if ($.jstree._reference(data.rslt.op).get_path(data.rslt.op).slice(0,1) == 'CBE Toolkit'){
         	var toolkit = true;
         	var setpointPaths = $.jstree._reference(data.rslt.op).get_path(data.rslt.op)
         }
         else {var setpointPaths = $.jstree._reference(data.rslt.op).get_path(data.rslt.op).slice(1)}
         setpointPaths.push($.jstree._reference(data.rslt.o[i]).get_text(data.rslt.o[i]))
         setpointPaths = setpointPaths.join().replace(new RegExp(",", "g"),'/')
         if (setpointPaths.slice(0,1) != '/'){setpointPaths = '/' + setpointPaths}
         $.jstree._reference(data.rslt.o[i]).set_text(data.rslt.o[i], setpointPaths)
         if (!toolkit){$('#searchExpressionText').val(setpointPaths)}
        })
        })
   $('#treeSelections').show().append('<input type="hidden" id="aggregate">')
}

function analysisPlot(){
    
    //get start and end time in milliseconds since epoch UTC
	getTimeRange();
	var wkd = document.getElementById("wkdays").checked;
	var sh = Number(document.getElementById("startHour").value);
	var eh = Number(document.getElementById("endHour").value);
	var ad = document.getElementById("alldays").checked;
	
	if (document.getElementById("analysisRadio1").checked){
		treeJSON = saveEconomizerTree();
		getEconomizerPaths();
		economizerAnalysis(wkd, sh, eh, ad);
		return;
	}
}

function economizerAnalysis(wkd, sh, eh, ad) {
	var resample_s = $('#resampleTime').val();
	//paths_dict --key [setpoint] value temp
	
	//clear all regions first
	$('#region1').html('')
	$('#region2').html('')
	$('#region3').html('')
	$('#region4').html('')
	$('#region5').html('')
	
		//block chart overlay
	$('#chart').block({ 
		css: { 
			border: 'none', 
		    padding: '15px', 
            backgroundColor: '#002e48', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .75, 
            color: '#fff' 
        }
    });
	
   	$.ajax({
		type: "POST",
		url: "/pmp/energy/",
		data: JSON.stringify({'paths_dict': paths_dict, 'start': global_start, 'end': global_end, 'resample_s': resample_s, 'sh': sh, 
		'eh':eh, 'ad':ad, 'wkd': wkd, 'projectId': sessvars.sessionObj['projectId'], 'analysisType':analysisType, 'min_oa_frac':$('#min_oa_frac').val(), 'error_margin':$('#error_margin').val(), 'chw_vlv_adj':$('#chw_vlv_adj').val()}),
		success: function(data){
		   	if (data.success == true){
				//console.log(data)
				var region_list = []
				for (var region in data.data){
				if (data.data[region].length > 0){
					var err = parseInt($('#error_margin').val())
					if (region == 'region1'){var s_name = "Region 1"; var s_subtitle="Economizer at Min OA"}
					else if (region == 'region2'){var s_name = "Region 2"; var s_subtitle="Economizer Modulates";}
					else if (region == 'region3'){var s_name = "Region 3"; var s_subtitle="Economizer at 100%";}
					else if (region == 'region4'){var s_name = "Region 4"; var s_subtitle="Integrated Economizer";}
					else {var s_name = "Region 5"; var s_subtitle="Economizer at Min OA"}
					region_list.push(region)
					var x_min = 200;
					var x_max = 0;
					for (i=0; i<data.data[region].length; i++){
						var new_min = Math.min.apply(null, data.data[region][i])
						var new_max = Math.max.apply(null, data.data[region][i])
						if (new_min < x_min){x_min = new_min;}
						if (new_max > x_max){x_max = new_max;}
					}
						
					//console.log(x_min)
					$('#'+region).highcharts({
						chart: {
		                type: 'scatter',
		                zoomType: 'xy'
			            },
			            title: {
			                text: s_name
			            },
			            subtitle: {
			            	text: s_subtitle
			            },
			            xAxis: {
			                title: {
			                    //enabled: true,
			                    text: 'MAT - Ideal (F)'
			                },
			                //startOnTick: true,
			                //endOnTick: true,
			                min: x_min - err,
			                max: x_max + err,
			                //showLastLabel: true
			            },
			            yAxis: {
			                title: {
			                    text: 'MAT - Actual (F)'
			                },
			                min: x_min - err,
			                max: x_max + err
			            },
			            legend: {
			                enabled: false,
			                layout: 'vertical',
			                align: 'left',
			                verticalAlign: 'top',
			                x: 60,
			                y: 60,
			                floating: true,
			                backgroundColor: '#FFFFFF',
			                borderWidth: 1
			            },
			            plotOptions: {
			                scatter: {
			                    marker: {
			                        radius: 5,
			                        states: {
			                            hover: {
			                                enabled: true,
			                                lineColor: 'rgb(100,100,100)'
			                            }
			                        }
			                    },
			                    states: {
			                        hover: {
			                            marker: {
			                                enabled: false
			                            }
			                        }
			                    },
			                    tooltip: {
			                        //headerFormat: '<b>{series.name}</b><br>',
			                        pointFormat: '{point.x} F, {point.y} F',
			                    }
			                }
			            },
			            credits: {enabled: false},
			            series: [{
			                name: 'Actual',
			                //color: 'rgba(223, 83, 83, .5)',
			                color: 'rgba(40,93,227,.5)',
			                data:  data.data[region]
			    
			            },
			            {
			                type: 'line',
			                name: 'Ideal',
			                color: 'green',
			                data: [[x_min-1,x_min-1], [x_max+1,x_max+1]],
			                marker: {
			                    enabled: false
			                },
			                states: {
			                    hover: {
			                        lineWidth: 0
			                    }
			                },
			                enableMouseTracking: false
			            },
			            {
			                type: 'line',
			                showInLegend: false,
			                lineWidth: 1,
			                //name: 'bottom error line',
			                color: 'green',
			                dashStyle: 'Dash',
			                data: [[x_min-1,x_min-1-err], [x_max+1,x_max+1-err]],
			                marker: {
			                    enabled: false
			                },
			                enableMouseTracking: false
			            },
			            {
			                type: 'line',
			                lineWidth: 1,
			                //name: 'top error line',
			                color: 'green',
			                dashStyle: 'Dash',
			                showInLegend: false,
			                data: [[x_min-1,x_min-1+err], [x_max+1,x_max+1+err]],
			                marker: {
			                    enabled: false
			                },
			                enableMouseTracking: false
			            }]
			            
						}) //end highcharts
					} //end if
				} //end for
				var p = Highcharts.charts.length - region_list.length
				for (var i=p; i<Highcharts.charts.length; i++){
					var chart1 = Highcharts.charts[i]
					
					if (region_list[i-p] == 'region1' || region_list[i-p] == 'region2'){
						tip_tl = 'Econ too<br> closed'
						tip_bl = 'Econ too<br> open'
					}
					else if (region_list[i-p] == 'region3' || region_list[i-p] == 'region4'){
						tip_tl = 'Return damper<br> not closed'
						tip_bl = 'Sensor error'
					}
					else{
						tip_tl = 'Econ too<br> open'
						tip_bl = 'Less than<br> min OA'
					}
					chart1.renderer.text(tip_tl, 70, 70).css({
					    fontSize: '8pt',
					    color: 'red'
					}).add();
					chart1.renderer.text(tip_bl, 200, 320).css({
					    fontSize: '8pt',
					    color: 'red'
					}).add();
				}
				
			} //end if
			else {alert('No valid data for this time range.');}
			//unblock the blocking overlay
    		$('#chart').unblock();
    	},
    	error: function(e){
    		alert('Problem with your query. Check that you have valid mappings setup.');
			//unblock the blocking overlay
    		$('#chart').unblock();
    	}
	});
	
}

function saveEconomizerTree(save){
	document.getElementById('projectId').value = sessvars.sessionObj['projectId']
	var treeJSON = $('#treeSelections').jstree("get_json");
	if (save){
		url = '/pmp/energy/';
		$.ajax({
			type: "POST",
			url: url,
			data: JSON.stringify({'form': $('form#configFile').serializeObject(), 'treeJSON': treeJSON}),
			datatype: "json",
			success: function(data){
				var configFileName = $('select#id_for_name').find("option:selected").text()
	            //reload drop-down list if the name is new
	            if (configFileName != $('#id_form_name').val()){$('#economizerHeading').html(data)}
				$('#success').html("<strong>&nbsp;&nbsp;Saved successfully</strong>").fadeIn().delay(2000).fadeOut(1000);        
			}
		});
	}
	else {return treeJSON}	
}

function getEconomizerPaths(){
	var mat_path = treeJSON[0].children[0].data
	var rat_path = treeJSON[1].children[0].data
	var oat_path = treeJSON[2].children[0].data
	var sat_path = treeJSON[3].children[0].data
	var sat_stpt_path = treeJSON[4].children[0].data
	try{ var chw_vlv_path = treeJSON[5].children[0].data }
	catch(err){var chw_vlv_path = ''}
	paths_dict = {'mat':mat_path, 'rat':rat_path, 'oat':oat_path, 'sat':sat_path, 'sat_stpt':sat_stpt_path,'chw_vlv':chw_vlv_path}
	//console.log(paths_dict);
}
